<template>
	<BaseFilter class="date-range-filter" :label="label">
		<view class="date-input flex-align-center" @click="showCalendar = true">
			<text class="date">{{ startDate }}</text>
			<view class="gutter" />
			<text class="date">{{ endDate }}</text>
			<u-icon name="calendar" color="#999999" size="32" style="margin-right: 20rpx;" />
		</view>
		<PopupCalendar
			v-if="showCalendar"
			:show="showCalendar"
			:label="label"
			:value="value"
			:color="color"
			type="range"
			:valueFormat="valueFormat"
			@input="onChange"
			@close="showCalendar = false"
		/>
	</BaseFilter>
</template>

<script>
	import style from 'uni.scss';
	import BaseFilter from './BaseFilter.vue';
	import PopupCalendar from './PopupCalendar.vue';
	const dayjs = require('dayjs');
	const customParseFormat = require('dayjs/plugin/customParseFormat');
	dayjs.extend(customParseFormat);

	export default {
		name: 'dateRangeFilter',
		props: {
			label: {
				type: String
			},
			value: {
				type: [Array]
			},
			color: {
				type: String,
				default: style.primary_color
			},
			confirmText: {
				type: String,
				default: '确定'
			},
			format: {
				type: String,
				default: 'YYYY-MM-DD'
			},
			valueFormat: {
				type: String,
				default: 'YYYY-MM-DD'
			}
		},
		components: {
			BaseFilter,
			PopupCalendar
		},
		data() {
			return {
				showCalendar: false
			}
		},
		methods: {
			onChange(value) {
				this.$emit('input', value);
				this.$emit('change', value);
			}
		},
		computed: {
			dayList() {
				function formatDate(value, format) {
					if (format === 'timestamp') {
						return dayjs(new Date(value));
					} else if (typeof value === 'string') {
						return dayjs(value, format);
					} else {
						return dayjs(value);
					}
				}
				return (this.value || []).map(item => {
					return formatDate(item, this.valueFormat);
				});
			},
			startDate() {
				let temp = this.dayList[0];
				return temp ? temp.format(this.format) : '开始日期';
			},
			endDate() {
				let temp = this.dayList[1];
				return temp ? temp.format(this.format) : '结束日期';
			}
		}
	}
</script>

<style scoped>
	.date-input {
		height: 72rpx;
		background: #F6F7F9;
		margin-top: 16rpx;
		border-radius: 8rpx;
	}

	.gutter {
		height: 2rpx;
		width: 24rpx;
		background: #999999;
		flex-grow: 0;
		flex-shrink: 0;
	}

	.date-input .date {
		width: 200rpx;
		flex-grow: 1;
		flex-shrink: 1;
		font-size: 28rpx;
		color: #999999;
		text-align: center;
		padding: 0px 20rpx;
	}
</style>